using System;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace WebSMS.Web.Core;

public class ApplicationFilter :ActionFilterAttribute
{
    public readonly IRepository<UserRuleLinks> _userRulelinksService;
    public readonly IRepository<RuleDataLinks> _ruleDataLinkService;
    public readonly IRepository<DataPo> _dataService;
    public ApplicationFilter( IRepository<DataPo> dataService,IRepository<UserRuleLinks> userRuleLinksService, IRepository<RuleDataLinks> ruleDataLinkService)
    {
        _userRulelinksService = userRuleLinksService;
        _ruleDataLinkService = ruleDataLinkService;
        _dataService = dataService;
    }

    /// <summary>
    /// 执行操作前后
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
        var httpContext = context.HttpContext;
        var userId = httpContext.User?.FindFirstValue("UserId");

        if (!String.IsNullOrEmpty(userId))
        { 
            var userRuleByUserId = from ur in _userRulelinksService
                    .Where(u => u.UserId == Guid.Parse(userId))
                join rd in _ruleDataLinkService.AsQueryable() on ur.RuleId equals rd.RuleId
                join d in _dataService.AsQueryable() on rd.DataTypeId equals d.Id
                select new
                {
                    RuleId = ur.RuleId,
                    DataTypeId = rd.DataTypeId,
                    DataType = d.DataType,
                };

            if (userRuleByUserId.Any())
            {
                foreach (var item in userRuleByUserId)
                {
                    var controllerName = actionDescriptor.ControllerName;

                    if (item.DataType.ToString() == controllerName)
                    {
                        context.Result = new ContentResult
                        {
                            Content = new ResponseObject<Object>().Fail(item.DataType.ToString(),"你没有权限查看该页面").ToString(),
                            ContentType = "application/json",
                            StatusCode = StatusCodes.Status403Forbidden
                        };
                        return;
                    }
                }
            }
        }

        await next(); // Proceed to the next middleware if no interception occurred
    }


    /// <summary>
    /// 返回结果前后
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        // 代码参考接口方式

        return base.OnResultExecutionAsync(context, next);
    }

}